package com.shanyu.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.shanyu.dao.IArticleDao;
import com.shanyu.dao.IArticleTagDao;
import com.shanyu.dao.ITagDao;
import com.shanyu.dto.ArticleDto;
import com.shanyu.eo.ArticleEo;
import com.shanyu.eo.ArticleTagEo;
import com.shanyu.eo.TagEo;
import com.shanyu.service.IArticleService;

@Service
public class ArticleServiceImpl implements IArticleService{

	@Autowired
	private IArticleDao articleDao;
	
	@Autowired
	private IArticleTagDao articleTagDao;
	
	@Autowired
	private ITagDao tagDao;
	
	public ArticleDto getArticleDetail(String articleId) throws Exception {
		// TODO Auto-generated method stub
		ArticleDto dto = new ArticleDto();
		
		ArticleEo article = articleDao.getById(articleId);
		
		if(2 != article.getStatus()){
			throw new Exception("文章不存在");
		}
		
		BeanUtils.copyProperties(article, dto);
		dto.setTagList(getTagList(articleId));
		//IncReadCount(articleId);
		return dto;
	}
	
	private List<TagEo> getTagList(String articleId){
		List<TagEo> res = new ArrayList<TagEo>();
		List<String> tagIds = new ArrayList<String>();
		ArticleTagEo query = new ArticleTagEo();
		query.setArticleId(articleId);
		List<ArticleTagEo> atList = articleTagDao.select(query);
		if(!CollectionUtils.isEmpty(atList)){
			for(ArticleTagEo atEo : atList){
				tagIds.add(atEo.getTagId());
			}
		}
		if(!CollectionUtils.isEmpty(tagIds)){
			List<TagEo> tagList = tagDao.selectByTagIds(tagIds);
			return tagList;
		}
		return null;
	}

	public void IncReadCount(String articleId) {
		// TODO Auto-generated method stub
		ArticleEo article = articleDao.getById(articleId);
		if(article != null){
			int readCount = article.getReadCount();
			article.setReadCount(readCount++);
		}
		articleDao.updateSelective(article);
	}

	public PageInfo getArticleByPage(String classificaId, int pageNum, int pageSize) {
		// TODO Auto-generated method stub
		PageInfo res = new PageInfo(null);
		List<ArticleDto> lists = new ArrayList<ArticleDto>();
		
		ArticleEo query = new ArticleEo();
		query.setClassificaId(classificaId);
		query.setStatus(2);
		PageInfo page = articleDao.page(query, pageNum, pageSize);
		List<ArticleEo> list = page.getList();
		for(ArticleEo eo : list){
			ArticleDto dto = new ArticleDto();
			BeanUtils.copyProperties(eo, dto);
			dto.setTagList(getTagList(eo.getId()));
			lists.add(dto);
		}
		BeanUtils.copyProperties(page, res);
		res.setList(lists);
		return res;
	}


}
